<template>
  <div style="width: 100%; margin-left: 10px">
    <!-- <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item> 报修管理 </el-breadcrumb-item>
      <el-breadcrumb-item>一键报修</el-breadcrumb-item>
    </el-breadcrumb> -->

    <titleNav></titleNav>
    <div
      style="
        width: 100%;
        display: flex;
        align-items: center;
        flex-direction: column;
      "
    >
      <el-card style="margin-top: 20px; width: 80%">
        <el-form
          :model="formData"
          :rules="rules"
          label-width="auto"
          ref="ruleFormRef"
        >
          <el-form-item
            v-for="item in form"
            :key="item.id"
            :label="item.labelName"
            :prop="item.params"
          >
            <el-input
              v-if="item.inputType == 'text'"
              v-model="formData[item.params]"
              :placeholder="'请输入：' + item.labelName"
            ></el-input>
            <el-select
              v-else-if="
                item.inputType == 'select' || item.inputType == 'multipleSelect'
              "
              v-model="formData[item.params]"
              :placeholder="'请输入：' + item.labelName"
              :multiple="item.inputType === 'multipleSelect'"
            >
              <el-option
                v-for="item in item.optionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <!-- <div v-else-if="item.inputType == 'voice'">
            <el-upload
              ref="refupload1"
              class="upload-demo"
              action="http://pc.zhihuibaoxiu.com/ybx/repair/uploadVoice"
              :headers="customHeaders"
              :http-request="uploadVoice"
              :on-exceed="handleExceed"
              :auto-upload="false"
              multiple
            >
              <template #trigger>
                <el-button type="primary">选择录音</el-button>
              </template>

              <el-button
                style="margin-left: 20px; margin-top: -5px"
                type="success"
                @click="submitUpload1()"
              >
                上传录音
              </el-button>
            </el-upload>
          </div> -->
            <div v-else-if="item.inputType == 'image'">
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                multiple
                :auto-upload="false"
                :http-request="uploadFile"
                :on-change="handleChange"
                :before-upload="beforeUpload"
              >
                <template #trigger>
                  <el-button type="primary">选择图片</el-button>
                </template>
              </el-upload>
            </div>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" style="margin-left: 40%"
            >取消</el-button
          >
          <el-button type="primary" @click="upload(ruleFormRef)">
            确定
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { addRepair, postPicture, getuseForm, postVioce } from '@/api/repairList'
import { useUserStore } from '@/stores/user.js'
import { useTitleStore } from '@/stores/titleNav.js'
import { ElMessage } from 'element-plus'
const userStore = useUserStore()
const titleStore = useTitleStore()

const index = ref({
  index: '/repairmanage/oneRepair',
  title: '一键报修'
})

const formData = ref({})
const form = ref([])
const ruleFormRef = ref()
const dialogVisible = ref(false)

// const refupload1 = ref([])

// const submitUpload1 = () => {
//   refupload1.value.submit()
//   formData.value = refupload1.value
// }
// const handleExceed = () => {
//   ElMessage({
//     message: '最多只能上传7张图片',
//     type: 'warning'
//   })
// }

const uploadRef = ref(null)
const uploadFiles = ref([])
const filesLength = ref(0)

const handleChange = (file, fileList) => {
  filesLength.value = fileList.length
  console.log(filesLength.value)
}

const formEltemp = ref()
const upload = async (formEl) => {
  formEltemp.value = formEl
  uploadRef.value[0].submit()
  if (!uploadRef.value[0].submit()) {
    const valid = await formEltemp.value.validate()
    console.log(valid)
    if (valid) {
      console.log('表单验证通过')
      setTimeout(async () => {
        formData.value.isSelf = 0
        const res = await addRepair(formData.value)
        if (res.code == 200) {
          ElMessage({
            message: '增加成功',
            type: 'success'
          })
          formData.value = {}
          dialogVisible.value = false
        } else {
          ElMessage({
            message: '未知错误，请联系管理员',
            type: 'warning'
          })
        }
        console.log(res)
      }, 1000) // 2000毫秒等于2秒
    } else {
      console.log('表单验证失败')
      // 表单验证失败，可以在这里添加错误处理逻辑
    }
  } else {
    uploadRef.value[0].submit()
  }
}
const customHeaders = ref({
  authorization: userStore.userInfo.token
})
const uploadFile = async (param) => {
  // 等待所有文件被选中后，再进行上传
  uploadFiles.value.push(param.file)
  if (uploadFiles.value.length === filesLength.value) {
    let fd = new FormData()
    // 将全部文件添加至FormData中
    uploadFiles.value.forEach((file) => {
      fd.append('file', file)
    })
    try {
      const res = await postPicture(fd)
      console.log(res)
      formData.value.pictureList = res.data
      const valid = await formEltemp.value.validate()
      console.log(valid)
      if (valid) {
        console.log('表单验证通过')
        setTimeout(async () => {
          formData.value.isSelf = 0
          const res = await addRepair(formData.value)
          if (res.code == 200) {
            ElMessage({
              message: '增加成功',
              type: 'success'
            })
            formData.value = {}
            dialogVisible.value = false
          } else {
            ElMessage({
              message: '未知错误，请联系管理员',
              type: 'warning'
            })
          }
          console.log(res)
        }, 1000) // 2000毫秒等于2秒
      } else {
        console.log('表单验证失败')
        // 表单验证失败，可以在这里添加错误处理逻辑
      }
    } catch (error) {
      console.error('Upload failed:', error)
    }
  }
}
const uploadVoice = async (param) => {
  // 等待所有文件被选中后，再进行上传
  uploadFiles.value.push(param.file)
  if (uploadFiles.value.length === filesLength.value) {
    let fd = new FormData()
    // 将全部文件添加至FormData中
    uploadFiles.value.forEach((file) => {
      fd.append('file', file)
    })
    try {
      const res = await postVioce(fd)
      console.log(res)
      formData.value.repairVoice = res.data
    } catch (error) {
      console.error('Upload failed:', error)
    }
  }
}
const rules = ref({})
const getForm = async () => {
  const res = await getuseForm()
  form.value = res.data.itemList
  form.value.forEach((item) => {
    if (item.required) {
      rules.value[item.params] = [
        {
          required: true,
          message: '请输入或选择' + item.labelName,
          trigger: 'blur'
        }
      ]
    }
  })
  formData.value.formId = res.data.formId
  console.log(rules.value)
}
onMounted(() => {
  titleStore.updataTitInfo(index)
  getForm()
})
</script>
<style scoped lang="less"></style>
